/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package org.elanfox.intellicommunity.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author allan
 * @date 06/12/2017
 */
public class JwtUtils {
    public static JWTCreator.Builder build(String iss) {
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(iss)
                .withIssuedAt(new Date());

        return builder;
    }

    /**
     * 签名得到一个token
     *
     * @param builder
     * @param secret
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String sign(JWTCreator.Builder builder, String secret) throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return builder.sign(algorithm);
    }

    public static DecodedJWT verify(String secret, String token) throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();

        return verifier.verify(token);
    }
}
